<?php

Yii::import('ext.search.interfaces.ISearchInterface');

class DbSearchAdapter implements ISearchInterface
{

    private $_db;

    public function __construct($db)
    {
	$this->_db = $db;
    }

    public function getDb()
    {
	return $this->_db;
    }

    public function deleteById($id)
    {
	if (!$id) {
	    return false;
	}
	$this->getDb()->createCommand()->delete('search_index', 'id = :id', array(':id' => $id));
    }

    public function search($query, $offset = 0, $limit = 10, $params = array())
    {
	if (empty($query)) {
	    return false;
	}
	$this->getDb()->createCommand()->reset();
	$sql = $this->getDb()->createCommand($params)
		->select('*')
		->from('search_index')
		->where("MATCH (`text`) AGAINST (" . $this->getDb()->quoteValue($query) . " IN BOOLEAN MODE)")
		->limit($limit, $offset);
	return $sql->queryAll();
    }

    public function toIndex(array $data)
    {
	if (empty($data)) {
	    return false;
	}
	$this->setAndUpdate($data);
    }

    public function setAndUpdate(array $data)
    {
	if (empty($data)) {
	    return false;
	}
	$duplicate = array();
	foreach ($data as $key => $value) {
	    $duplicate[] = $key . '=VALUES(' . $key . ')';
	}

	$data = array_map(array($this->getDb(), 'quoteValue'), $data);
	$sql = "INSERT INTO `search_index`(`" . implode("`, `", array_keys($data)) . "`) 
		VALUES(" . implode(",", array_values($data)) . ")
		ON DUPLICATE KEY UPDATE " . implode(", ", $duplicate) . "";
	return $this->getDb()->createCommand()->setText($sql)->execute();
    }

}
